﻿using AutoMapper;
using InventoryIssue.API.Write.Application.Command.Stocktaking;
using InventoryIssue.Domain;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using InventoryIssue.Infrastructrue.Interface;
using MediatR;
using NetTaste;
using Newtonsoft.Json.Linq;
using System.Security.Claims;

namespace InventoryIssue.API.Write.Application.Handler.Stocktaking
{
    public class CreateStocktakingHandler : IRequestHandler<CreateStocktakingCommand, APIResult<int>>
    {
        private readonly IMapper mapper;
        private readonly DatabaseContext db;
        private readonly IHttpContextAccessor httpContextAccessor;

        public CreateStocktakingHandler(IMapper mapper, DatabaseContext db,IHttpContextAccessor httpContextAccessor)
        {
            this.mapper = mapper;
            this.db = db;
            this.httpContextAccessor = httpContextAccessor;
        }
        public async Task<APIResult<int>> Handle(CreateStocktakingCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            await db.SqlSugar.Ado.BeginTranAsync();
            var model = mapper.Map<StocktakingModel>(request);
            var OrderCreatorClaim = httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
            //if (!int.TryParse(OrderCreatorClaim, out int orderCreator))
            //{
            //    result.Code = APIEnum.Fail;
            //    result.Message = "无法获取有效的用户ID";
            //    return await Task.FromResult(result);
            //}
            //model.OrderCreator = OrderCreatorClaim;
            var res = db.SqlSugar.Queryable<StocktakingModel>().Where(x => x.StocktakingId == model.StocktakingId).First();
            if (res != null)
            {
                result.Message = "该盘点编号已存在!";
                result.Code = APIEnum.Fail;
                return await Task.FromResult(result);
            }
            int r = await db.SqlSugar.Insertable(model).ExecuteCommandAsync();
            var stocktakingProductModel = request.Products.Select(code => new StocktakingProductModel
            {
                StocktakingId = request.StocktakingId,
                ProductId = code.ProductId,
                IsDel = false
            }).ToList();
            int r1 = await db.SqlSugar.Insertable(stocktakingProductModel).ExecuteCommandAsync();
            await db.SqlSugar.Ado.CommitTranAsync();
            if (r > 0)
            {
                result.Message = "添加成功";
                result.Data = r;
                result.Code = APIEnum.Ok;
            }
            else
            {
                result.Message = "添加失败";
                result.Data = r;
                result.Code = APIEnum.Fail;
            }
            return await Task.FromResult(result);
        }
    }
}
